package com.lagou.edu.homework.service.impl;

import com.lagou.edu.homework.dao.LagouAuthCodeDao;
import com.lagou.edu.homework.service.LagouAuthCodeService;
import com.lagou.edu.pojo.LagouAuthCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Service
public class LagouAuthCodeServiceImpl implements LagouAuthCodeService {

    @Autowired
    private LagouAuthCodeDao authCodeDao;

    /**
     * 保存发送的验证码
     *
     * @param authCode
     * @return
     */
    @Override
    public Boolean saveAuthCode(LagouAuthCode authCode) {
        LagouAuthCode result = authCodeDao.save(authCode);
        return result.getId() != 0;
    }

    /**
     * 校验邮箱和验证码
     *
     * @param email
     * @param code
     * @return
     */
    @Override
    public Boolean validateEmailAndCode(String email, String code) {
        LagouAuthCode authCode = new LagouAuthCode();
        authCode.setEmail(email);
        authCode.setCode(code);

        Example<? extends LagouAuthCode> example = Example.of(authCode);
        Optional<? extends LagouAuthCode> authCodeOptional = authCodeDao.findOne(example);
        if (authCodeOptional.isPresent()) {
            LagouAuthCode authCodeOne = authCodeOptional.get();
            return authCodeOne.getExpiretime() > System.currentTimeMillis();
        }
        return false;
    }

    /**
     * 校验该邮件是否有1分钟内发送的验证码
     *
     * @param email
     * @return
     */
    @Override
    public Boolean validateByEmail(String email) {
        LagouAuthCode authCode = new LagouAuthCode();
        authCode.setEmail(email);

        Example<? extends LagouAuthCode> example = Example.of(authCode);
        Optional<? extends LagouAuthCode> authCodeOptional = authCodeDao.findOne(example);
        if (authCodeOptional.isPresent()) {
            LagouAuthCode authCodeOne = authCodeOptional.get();
            return System.currentTimeMillis() - authCodeOne.getExpiretime() <= 60 * 1000;
        }
        return false;
    }
}
